import React, { Component } from 'react';
import TemplateHoc from '../component/template-hoc';
import Header from './header';
import List from './expense-adjunct-list'
import { deepCopy } from 'share/common';
import ExpenseAdjunctService from './expense-adjunct-service';

@TemplateHoc
class ExpenseAdjunctList extends Component {

  static contextTypes = {
    currentExpense: React.PropTypes.object,
    isWaitForAudit: React.PropTypes.bool
  };

  constructor(props) {
    super(props);
    this.state = {
      ...this.initData(props)
    };
  }

  initData = (props) => {
    const { mergeAdjuncts, receiptLabels} = props;
    return {
      mergeAdjuncts: deepCopy(mergeAdjuncts),
      receiptLabels,
      labelFilter: []
    };
  };

  componentWillReceiveProps(nextProps) {
    nextProps.randomHash !== this.props.randomHash && this.setState({ ...this.initData(nextProps) });
  };

  handleHeaderChange = (params) => {
    const { isCheckRead, labelFilter } = params;
    const { currentExpense } = this.context;
    const { mergeAdjuncts } = this.state;
    if (isCheckRead) {
      this.props.changeMode(false);
      return;
    }
    ExpenseAdjunctService.resetData(currentExpense, labelFilter, mergeAdjuncts);
    this.setState({ labelFilter, mergeAdjuncts });
  };

  render() {
    const {receiptLabels, leftWidth, receiptLabelsDesc, annotates, receiptChanges, handleJumpRead, refreshAnnotate, randomHash } = this.props;
    const { labelFilter, mergeAdjuncts } = this.state;

    return (
      <section className="expense-adjunct-list-mode">
        <Header
          mergeAdjuncts={mergeAdjuncts}
          receiptLabels={receiptLabels}
          labelFilter={labelFilter}
          onChange={this.handleHeaderChange}
          leftWidth={leftWidth}
          randomHash={randomHash}
          ref={'header'}
        />

        <List
          receiptLabelsDesc={receiptLabelsDesc}
          receiptChanges={receiptChanges}
          annotates={annotates}
          mergeAdjuncts={mergeAdjuncts}
          handleJumpRead={handleJumpRead}
          refreshAnnotate={refreshAnnotate}
          onInvoiceChange={this.props.onInvoiceChange}
          randomHash={randomHash}
          key={labelFilter.length} // for refresh
        />
      </section>
    );
  }
}

ExpenseAdjunctList.propTypes = {};

export default ExpenseAdjunctList;
